<?php

namespace App\Http\Controllers\Admin;

use App\Models\ArticleCate;
use App\Services\ArticleService;

use Illuminate\Http\Request;

class ArticleController extends BaseController
{
    public function initialize(Request $request)
    {
        parent::initialize($request);

        $defaultWhere = $this->getDefaultWhere();
        $defaultWhere[] = ['status', '<>', 90];
        $this->defaultWhere = $defaultWhere;

        // 文章分类
        $articleCates = ArticleCate::where('status', 1)->orderBy('created_at', 'desc')->get(['id', 'name']);
        view()->share('articleCates', $articleCates);
    }

    /**
     * 导出数据
     */
    public function export(Request $request)
    {
        $result = ArticleService::export([], $request->all());
        if ($result['code'] == 2) {
            return redirect('admin/article')->with('error', $result['msg']);
        }

        return response()->json($result);
    }

    /**
     * 处理列表数据
     */
    public function handleListData($data)
    {
        $className = '\\App\\Models\\' . $this->model;
        $model = new $className;

        $data = $model->formatDatas($data, ['format_source' => 'backend']);

        return $data;
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request)
    {
        $param = $request->all();
        $where = [];
        if (isset($param['name']) && $param['name']) {
            $where[] = ['name', 'like', '%' . trim($param['name']) . '%'];
        }
        if (isset($param['cate_id']) && $param['cate_id']) {
            $where[] = ['cate_id', '=', $param['cate_id']];
        }
        if (isset($param['range_date']) && $param['range_date']) {
            $rangeDate = explode(' ~ ', $param['range_date']);
            $where[] = ['created_at', '>=', strtolower($rangeDate[0])];
            $where[] = ['created_at', '<=', strtotime($rangeDate[1])];
        }

        return $where;
    }
}
